#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
using namespace std;
class Solution {
    int m, n;
    int dfx[4] = { 0,0,1,-1 };
    int dfy[4] = { 1,-1,0,0 };
public:
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& h) {
        m = h.size();
        n = h[0].size();
        vector<vector<bool>> pac(m, vector<bool>(n));
        vector<vector<bool>> ath(m, vector<bool>(n));
        for (int i = 0; i < m; i++)
        {
            dfs(h, i, 0, pac);
        }
        for (int j = 0; j < n; j++)
        {
            dfs(h, 0, j, pac);
        }
        for (int i = 0; i < m; i++)
        {
            dfs(h, i, n - 1, ath);
        }
        for (int j = 0; j < n; j++)
        {
            dfs(h, m - 1, j, ath);
        }
        vector<vector<int>> ret;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (pac[i][j] && ath[i][j])
                {
                    ret.push_back({ i,j });
                }
            }
        }
        return ret;
    }
    void dfs(vector<vector<int>>& h, int i, int j, vector<vector<bool>>& as)
    {
        as[i][j] = true;
        for (int k = 0; k < 4; k++)
        {
            int x = i + dfx[k];
            int y = j + dfy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && !as[x][y] && h[x][y] >= h[i][j])
            {
                dfs(h, x, y, as);
            }
        }
    }
};